<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>{{ $t('product.upsert.basic') }}</h3>
      <el-form ref="dataForm" :rules="basicRules" :model="product" label-width="150px">
        <el-form-item :label="$t('product.upsert.title')" prop="title">
          <el-input v-model="product.title" />
        </el-form-item>
        <el-form-item :label="$t('product.upsert.img')" prop="img">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handleImgUrl"
            :show-file-list="false"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture-card"
          >
            <img v-if="product.img" :src="product.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('product.upsert.description')" prop="description">
          <el-input v-model="product.description" />
        </el-form-item>

      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>{{ $t('product.upsert.dataPoint') }}</h3>
      <el-button :plain="true" type="primary" @click="handleAddDataPoint">{{ $t('product.upsert.create') }}</el-button>
      <el-table :data="dataPoints">
        <el-table-column property="title" :label="$t('product.upsert.title')" />
        <el-table-column property="idTag" :label="$t('product.upsert.idTag')" />
        <el-table-column property="type" :label="$t('product.upsert.type')" />
        <el-table-column property="refreshPeriod" :label="$t('product.upsert.refreshPeriod')" />
        <el-table-column property="period" :label="$t('product.upsert.period')" />
        <el-table-column
          align="center"
          label="操作"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="doDeleteDataPoint(scope.$index)">{{ $t('product.upsert.deletE') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="dataPointVisiable" :title="$t('product.upsert.createDataPoint')">
        <el-form
          ref="dataPointForm"
          :model="dataPointForm"
          :rules="dataPointRules"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item :label="$t('product.upsert.title')" prop="title">
            <el-input v-model="dataPointForm.title" />
          </el-form-item>
          <el-form-item :label="$t('product.upsert.idTag')" prop="idTag">
            <el-input v-model="dataPointForm.idTag" />
            <el-tooltip class="item" effect="dark" :content="$t('product.upsert.idTagAsk')" placement="top-start">
              <i class="el-icon-question" />
            </el-tooltip>
          </el-form-item>
          <el-form-item :label="$t('product.upsert.type')" prop="type">
            <el-select v-model="dataPointForm.type" :placeholder="$t('product.upsert.placeholdertype')">
              <el-option
                v-for="item in dataPointTypeDic"
                :key="item.type"
                :label="$t(item.title)"
                :value="item.type"
              />
            </el-select></el-form-item>
          <el-form-item :label="$t('product.upsert.refreshPeriod')" prop="refreshPeriod">
            <el-input v-model.number="dataPointForm.refreshPeriod">
              <template slot="append">{{ $t('product.upsert.refreshPeriodUnit') }}</template>
            </el-input>
            <el-tooltip class="item" effect="dark" :content="$t('product.upsert.refreshPeriodAsk')" placement="top-start">
              <i class="el-icon-question" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="$t('product.upsert.refreshPeriodDef')" placement="top-start">
              <i class="el-icon-question" />
            </el-tooltip>
          </el-form-item>
          <el-form-item :label="$t('product.upsert.period')" prop="period">
            <el-input v-model.number="dataPointForm.period">
              <template slot="append">{{ $t('product.upsert.second') }}</template>
            </el-input>
            <el-tooltip class="item" effect="dark" :content="$t('product.upsert.periodAsk')" placement="top-start">
              <i class="el-icon-question" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="$t('product.upsert.periodDef')" placement="top-start">
              <i class="el-icon-question" />
            </el-tooltip>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dataPointVisiable = false">{{ $t('product.upsert.cancel') }}</el-button>
          <el-button type="primary" @click="doDataPointCreate">{{ $t('product.upsert.confirm') }}</el-button>
        </div>
      </el-dialog>
    </el-card>

    <div class="op-container">
      <el-button @click="$router.push({ path: '/product/list' })">{{ $t('product.upsert.cancel') }}</el-button>
      <el-button :loading="submitting" type="primary" @click="doUpsert">{{ product.id ? $t('product.upsert.updateProduct') : $t('product.upsert.createProduct') }}</el-button>
    </div>
  </div>
</template>

<script>
import { createProduct, detailProduct, editProduct } from '@/api/product'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'

const dataPointTypeDic = [{ type: 1, title: 'product.upsert.datatype.integer' }, { type: 2, title: 'product.upsert.datatype.string' }, { type: 3, title: 'product.upsert.datatype.float' }]
export default {
  name: 'ProductUpsert',
  data() {
    return {
      // 常量
      uploadPath,
      dataPointTypeDic,
      // 变量
      // 基本信息
      product: {
        title: '',
        img: '',
        description: ''
      },
      basicRules: {
        title: [
          { required: true, message: this.$t('product.upsert.ruleTitle'), trigger: 'blur' }
        ],
        img: [
          { required: true, message: this.$t('product.upsert.ruleImg'), trigger: 'blur' }
        ]
      },
      submitting: false,
      // 数据点
      dataPoints: [],
      dataPointVisiable: false,
      dataPointForm: {
        title: '',
        idTag: '',
        type: '',
        refreshPeriod: '',
        period: ''
      },
      dataPointRules: {
        title: [
          { required: true, message: this.$t('product.upsert.ruleTitle'), trigger: 'blur' }
        ],
        idTag: [
          { required: true, message: this.$t('product.upsert.ruleIdTag'), trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('product.upsert.ruleType'), trigger: 'blur' }
        ],
        refreshPeriod: [
          { required: true, message: this.$t('product.upsert.ruleRefreshPeriod'), trigger: 'blur' },
          { type: 'number', message: this.$t('rule.number') }
        ],
        period: [
          { required: true, message: this.$t('product.upsert.rulePeriod'), trigger: 'blur' },
          { type: 'number', message: this.$t('rule.number') }
        ]
      }
    }
  },
  computed: {
    headers() {
      return {
        DEVELOPERTOKEN: getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const productId = this.$route.query.productId
      if (productId) {
        detailProduct(productId)
          .then(res => {
            this.dataPoints = res.data.dataList
            console.log(this.dataPoints)
            res.data.dataList = undefined
            this.product = Object.assign({}, res.data)
          })
      }
    },
    handleAddDataPoint() {
      this.dataPointForm = {
        title: '',
        idTag: '',
        type: '',
        refreshPeriod: undefined,
        period: undefined
      }
      this.dataPointVisiable = true
    },
    doDeleteDataPoint(index) {
      // 删除数据点
      this.dataPoints.splice(index, 1)
    },
    doDataPointCreate() {
      this.$refs.dataPointForm.validate(valid => {
        if (valid) {
          if (this.dataPointForm.refreshPeriod * 10 * this.dataPointForm.period > 600) {
            this.$notify({
              title: this.$t('message.fail'),
              message: this.$('product.upsert.periodTooShort'),
              type: 'error'
            })
            return
          }
          const point = Object.assign({}, this.dataPointForm)
          this.dataPoints.push(point)
          this.dataPointVisiable = false
        }
      })
    },
    doUpsert(action) {
      this.$refs.dataForm.validate(valid => {
        // 表单校验
        if (valid) {
          // 组装devDTO
          this.submitting = true
          const devDto = {
            id: this.product.id,
            title: this.product.title,
            img: this.product.img,
            description: this.product.description,
            dataList: this.dataPoints
          }

          const f = this.product.id ? editProduct : createProduct
          f(devDto)
            .then(res => {
              this.$notify({
                title: this.$t('message.success'),
                message: this.$t(this.product.id ? 'product.upsert.editSuccess' : 'product.upsert.createSuccess'),
                type: 'success'
              })
              this.submitting = false
              this.$router.push({ path: '/product/list' })
            }).catch(e => {
              this.submitting = false
            })
        }
      })
    },
    handleImgUrl(response, file, fileList) {
      if (response.errno === 200) {
        console.log(response)
        this.product.img = response.url
      }
    },
    dataPointTypeFilter(type) {
      return dataPointTypeDic[type - 1]
    }
  }
}
</script>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>
